package com.xiliubit.cloudpicture.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiliubit.cloudpicture.api.aliyunai.AliYunAiApi;
import com.xiliubit.cloudpicture.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.xiliubit.cloudpicture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.xiliubit.cloudpicture.common.DeleteRequest;
import com.xiliubit.cloudpicture.constant.CacheNameConstant;
import com.xiliubit.cloudpicture.exception.BusinessException;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import com.xiliubit.cloudpicture.manager.CacheManager;
import com.xiliubit.cloudpicture.manager.CosManager;
import com.xiliubit.cloudpicture.manager.upload.FIlePictureUpload;
import com.xiliubit.cloudpicture.manager.upload.PictureUploadTemplate;
import com.xiliubit.cloudpicture.manager.upload.UrlPictureUpload;
import com.xiliubit.cloudpicture.mapper.PictureMapper;
import com.xiliubit.cloudpicture.model.dto.file.PictureUploadResult;
import com.xiliubit.cloudpicture.model.dto.picture.*;
import com.xiliubit.cloudpicture.model.dto.user.UserQueryRequest;
import com.xiliubit.cloudpicture.model.entity.Picture;
import com.xiliubit.cloudpicture.model.entity.Space;
import com.xiliubit.cloudpicture.model.entity.User;
import com.xiliubit.cloudpicture.model.enums.PictureReviewStatusEnum;
import com.xiliubit.cloudpicture.model.vo.PictureVO;
import com.xiliubit.cloudpicture.model.vo.UserInfoVO;
import com.xiliubit.cloudpicture.service.PictureService;
import com.xiliubit.cloudpicture.service.SpaceService;
import com.xiliubit.cloudpicture.service.UserService;
import com.xiliubit.cloudpicture.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 86173
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-07-30 15:17:32
*/
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService{

//    @Resource
//    private FileManager fileManager;

    @Resource
    private FIlePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;

    @Resource
    private CosManager cosManager;

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private CacheManager cacheManager;

    @Value("${defaultAvatar}")
    private String defaultAvatar;

    /**
     * 上传图片
     * @param inputSource  图片
     * @param pictureUploadRequest 前端传来的图片信息
     * @param user  用户
     * @return 图片信息
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User user) {
        ThrowUtils.throwIf(inputSource == null, ErrorCode.PARAMS_ERROR, "请上传图片");
        ThrowUtils.throwIf(user == null, ErrorCode.NO_AUTH_ERROR);
        /*         先获取参数：
         *            spaceId 为 null 代表上传到公共图库, 否则为上传到个人空间
         *            pictureId 为 null 代表新增图片, 否则为更新图片
         * */
        Long spaceId = null;
        Long pictureId = null;
        if (pictureUploadRequest != null){
            pictureId = pictureUploadRequest.getId();
            spaceId = pictureUploadRequest.getSpaceId();
        }

        if (spaceId != null) {
            // 上传到个人空间
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 校验空间权限, 替换为sa-token校验
//            spaceService.checkSpaceAuth(user, space);

            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间容量不足");
            }
        }

        // 判断是上传图片还是更新图片
        Picture oldPicture = null;
        if (pictureId != null) {
            // pictureUploadRequest存在
            oldPicture = this.getById(pictureUploadRequest.getId());
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅限本人或管理员可编辑(已改为使用sa-token校验)
//            if (!user.getId().equals(oldPicture.getUserId()) && !userService.isAdmin(user)) {
//                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//            }
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }

        String uploadPathPrefix;
        // 上传图片
        if (spaceId == null) {
            // 上传到公共图库
            uploadPathPrefix = "public/" + user.getId();
        } else {
            // 上传到个人空间
            uploadPathPrefix = "space/" + spaceId;
        }

        // 判断是否是url
        PictureUploadTemplate pictureUpload = filePictureUpload;
        if (inputSource instanceof String){
            pictureUpload = urlPictureUpload;
        }
        // 上传图片
        PictureUploadResult pictureUploadResult = pictureUpload.putPicture(inputSource, uploadPathPrefix);
        // 封装属性
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUploadResult, picture);
        picture.setUserId(user.getId());
        picture.setSpaceId(spaceId);
        // 判断图片名称是否指定
        String picName = pictureUploadRequest.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(picName)){
            // 指定名称
            picture.setName(picName);
        }
        // 判断是否是更新
        if (pictureId != null){
            // 是更新，补充id和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date()); // 编辑时间，Date类的格式化类似于2023-07-30 15:17:32，新建时默认为创建时间
        }
        // 补充审核参数
        this.fillReviewParams(picture, user);
        // 开启事务
        Picture finalOldPicture = oldPicture;
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalCount = totalCount + 1")
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            if (finalOldPicture != null) {
                // 删除旧照片
                cosManager.deleteObject(finalOldPicture.getUrl());
                cosManager.deleteObject(finalOldPicture.getThumbnailUrl());
            }
            return picture;
        });
        return PictureVO.objToVo(picture);
    }

    /**
     *  封装图片信息,包括创建用户信息
     * @param picture 图片信息
     * @param request 请求
     * @return 脱敏后的图片信息
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = picture.getUserId();
        if (userId >0 && userId != null){
            UserInfoVO userInfoVO = userService.getUserById(userId);
            pictureVO.setUser(userInfoVO);
        }
        return pictureVO;
    }

    /**
     * 获取查询包装类
     *
     * @param pictureQueryRequest 分页查询请求包装类
     * @return 查询包装类
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper <Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null){
            return queryWrapper;
        }

        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        List<String> tags = pictureQueryRequest.getTags();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)){
            // 拼接查询条件
            queryWrapper.and(qw -> qw
                    .like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }

        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picFormat), "picFormat", picFormat);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);

        // 查询编辑时间 ==>   startEditTime <= 编辑时间 < endEditTime
        queryWrapper.ge(ObjectUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjectUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");

        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)){
            for(String tag : tags){
                queryWrapper.like("tags","\"" + tag + "\"");
            }
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField),sortOrder.equals(UserQueryRequest.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    /**
     * 将分页查询的图片结果脱敏为VO对象
     * @param page  未脱敏的图片分页结果
     * @param request 请求
     * @return 脱敏后的图片分页结果
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> page, HttpServletRequest request){

        List<Picture> pictureList = page.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(page.getCurrent(), page.getSize(),page.getTotal());
        if (pictureList.isEmpty()){
            return pictureVOPage;
        }
        // 封装到VO
        List<PictureVO> pictureVOList = pictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());

        // 获取用户信息
        Set<Long> userIdList = pictureList.stream()
                .map(Picture::getUserId)
                .collect(Collectors.toSet());
        List<User> userList = userService.listByIds(userIdList);
        List<UserInfoVO> userVOList = userService.getUserVOList(userList);
        Map<Long, UserInfoVO> userInfoVOMap = userVOList.stream()
                .collect(Collectors.toMap(UserInfoVO::getId, userVO -> userVO));

        // 为每个pictureVO设置userInfoVO
        pictureVOList.forEach(pictureVO -> {
            if (userInfoVOMap.containsKey(pictureVO.getUserId())){
                pictureVO.setUser(userInfoVOMap.get(pictureVO.getUserId()));
            }
        });

        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 校验图片数据(用于更新和修改图片)
     * @param picture  图片
     */
    @Override
    public void validPicture(Picture picture){
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id不能为空,有参数校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id不能为空");
        if (StrUtil.isNotBlank(url)){
            ThrowUtils.throwIf(url.length()> 1024, ErrorCode.PARAMS_ERROR, "url过长");
        }
        if (StrUtil.isNotBlank(introduction)){
            ThrowUtils.throwIf(introduction.length()> 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 图片审核
     * @param pictureReviewRequest 图片审核请求
     * @param loginUser  登录用户
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser){
        //1. 参数校验
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (pictureReviewRequest == null || id == null || PictureReviewStatusEnum.REVIEW.equals(reviewStatusEnum)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2. 查询图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //3. 查询图片状态判断是否为重复审核
        if (oldPicture.getReviewStatus().equals(reviewStatus)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        //4. 更新审核状态
        Picture newPicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, newPicture);
        // 填充审核信息
        newPicture.setReviewerId(loginUser.getId());
        newPicture.setReviewTime(new Date());
        boolean result = this.updateById(newPicture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 清理公共图库的缓存
        cacheManager.clearCacheByPrefixWithScan(CacheNameConstant.PUBLIC_CACHE_NAME);
    }

    /**
     * 填充审核信息
     * @param picture  图片
     * @param loginUser  登录用户
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser){
        if (userService.isAdmin(loginUser)){
            // 如果是管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
        }else {
            //如果是用户，则需要审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEW.getValue());
        }
    }

    /**
     * 批量上传图片
     * @param pictureUploadByBatchRequest  图片上传请求
     * @param loginUser  登录用户
     * @return  上传成功的图片数量
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 1. 参数校验
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        int count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "上传图片数量不能超过30");
        // 2. 获取图片url数组
        // 要抓取的地址
        String searchText = pictureUploadByBatchRequest.getSearchText();
        // 避免查询关键字为null
        if (StringUtils.isBlank(searchText)){
            searchText = "";
        }
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1",searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        ThrowUtils.throwIf(ObjUtil.isNull(div), ErrorCode.OPERATION_ERROR, "获取元素失败");
        Elements select = div.select("img.mimg");
        // 统计获取了几张图片
        int uploadCount = 0;
        // 批量上传图片
        for (Element imgElement : select) {
            // 获取图片的src属性值,也就是url
            String url = imgElement.attr("src");
            if (StrUtil.isBlank(url)){
                log.info("图片url为空,已跳过：{}",url);
                continue;
            }
            // 去掉url的后缀
            int QuestionMarkIndex = url.lastIndexOf("?");
            // 记得校验原本的url是否有后缀查询参数
            if (QuestionMarkIndex != -1){
                url = url.substring(0, QuestionMarkIndex);
            }
            // 判断是否指定图片名称
            String picName = pictureUploadByBatchRequest.getPicName();
            if (StringUtils.isNotBlank(picName)){
                picName = picName + (uploadCount + 1);
            }else if (StringUtils.isNotBlank(searchText)) {
                picName = searchText + (uploadCount + 1);
            }else {
                picName = "默认" + (uploadCount + 1);
            }
            // 构造参数
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setPicName(picName);
            PictureVO pictureVO = null;
            try {
                // 上传图片
                pictureVO = this.uploadPicture(url, pictureUploadRequest, loginUser);
                log.info("图片上传成功: id = {}",pictureVO.getId());
            } catch (Exception e) {
                log.info("图片上传失败:",e);
                continue;
            }
            Picture picture = PictureVO.voToObj(pictureVO);
            // 设置图片名称
            picture.setName(searchText);
            uploadCount++;
            // 判断是否获取足够图片
            if (uploadCount >= count) {
                break;
            }
        }

        // 4. 返回抓取的图片个数
        return uploadCount;
    }

    /**
     * 异步删除图片文件
     * @param oldPicture  图片
     */
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 在一般的系统中需要先判断该图片是否被多条记录调用，如果被多条记录调用则不能删除

        //删除webp文件
        String url = oldPicture.getUrl();
        cosManager.deleteObject(url);
        //删除缩略图文件
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        cosManager.deleteObject(thumbnailUrl);
    }

    @Override
    public void checkPictureAuth(Picture picture, User loginUser) {
        Long userId = loginUser.getId();
        Long spaceId = picture.getSpaceId();

        if (spaceId == null) {
            // 公共图库, 管理员和创建者可以操作
            if (!userId.equals(picture.getUserId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 个人空间, 仅空间管理员可操作
            Space space = spaceService.getById(spaceId);
            // 校验权限
            spaceService.checkSpaceAuth(loginUser, space);
        }
    }

    @Override
    public boolean deletePicture(DeleteRequest deleteRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        // 判断图片是否存在
        Picture oldPicture = this.getById(deleteRequest.getId());
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        Long pictureId = deleteRequest.getId();
        // 校验权限, 替换为sa-token校验
//        this.checkPictureAuth(oldPicture, loginUser);
        // 开启事务
        Boolean b = transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = oldPicture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 删除cos图片文件
        this.clearPictureFile(oldPicture);
        // 清理缓存
        if (ObjUtil.isNotNull(oldPicture.getSpaceId())){
            cacheManager.clearCacheByPrefixWithScan(CacheNameConstant.SPACE_CACHE_NAME);
        }else {
            cacheManager.clearCacheByPrefixWithScan(CacheNameConstant.PUBLIC_CACHE_NAME);
        }
        return Boolean.TRUE.equals(b);
    }

    /**
     * 根据图片颜色搜索图片
     *
     * @param picColor  图片颜色
     * @param spaceId   空间id
     * @param loginUser 登录用户
     * @return 图片列表
     */
    @Override
    public List<PictureVO> searchPictureByColor(String picColor, Long spaceId, User loginUser) {
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        // 校验空间参数和权限, 替换为sa-token校验
//        spaceService.checkSpaceAuth(loginUser, space);
        // 查询该空间下的所有图片
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为Color对象
        Color targetColor = Color.decode(picColor);
        // 计算相似度（欧几里得距离）
        List<Picture> sortedPictures = pictureList.stream().sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pitureColor = Color.decode(hexColor);
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pitureColor);
                }))
                // 取前12个
                .limit(12)
                .collect(Collectors.toList());
        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    /**
     * 批量修改图片信息
     *
     * @param pictureEditByBatchRequest 图片信息
     * @param loginUser                 登录用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        // 校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        if (CollUtil.isEmpty(pictureIdList)){
            return;
        }
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        // 校验空间参数和权限, 替换为sa-token校验
//        spaceService.checkSpaceAuth(loginUser, space);
        // 查询图片中需要的字段
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        // 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)){
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        // 更新图片名称
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 批量更新 -- 因为每次更新的图片数量不多，这里就不使用分批次更新了
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 批量更新图片名称
     *
     * @param pictureList 图片列表
     * @param nameRule    名称规则
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (StrUtil.isBlank(nameRule) || ObjectUtil.isEmpty(pictureList)){
            return;
        }
        int count = 1;
        try {
            for (Picture picture : pictureList){
                String pictureName = nameRule.replace("{序号}", String.valueOf(count));
                picture.setName(pictureName);
                count++;
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }

    /**
     * 创建图片外绘任务
     *
     * @param createPictureOutPaintingTaskRequest 图片外绘任务请求参数
     * @param loginUser                           登录用户
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId))
                .orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));
        // 权限校验, 替换为sa-token校验
//        checkPictureAuth(picture, loginUser);
        // 构造请求参数
        CreateOutPaintingTaskRequest taskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        taskRequest.setInput(input);
        BeanUtil.copyProperties(createPictureOutPaintingTaskRequest, taskRequest);
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(taskRequest);
    }

    /**
     * 上传头像
     *
     * @param multipartFile 文件
     * @param loginUser     登录用户
     * @return 头像信息
     */
    @Override
    public String uploadAvatar(MultipartFile multipartFile, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "请上传图片");
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);

        // 检查上传次数
        Long userId = loginUser.getId();
        boolean result = cacheManager.checkTimesOfAvatarUpload(userId);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "今日上传次数已用完");
        // 构造参数
        String uploadPathPrefix = "avatar/" + userId;
        // 上传图片
        PictureUploadTemplate pictureUpload = filePictureUpload;
        PictureUploadResult pictureUploadResult = pictureUpload.putPicture(multipartFile, uploadPathPrefix);
        //如果不是默认头像，就删除旧的头像
        String userAvatar = loginUser.getUserAvatar();
        if (!StrUtil.equals(userAvatar, defaultAvatar) && StrUtil.isNotBlank(userAvatar)) { // 校验旧头像，非空，不是默认头像
            // 删除旧头像
            cosManager.deleteObject(userAvatar);
            // 因为头像url是缩略图，得到原图url
            String userAvatarUrl = userAvatar.replaceAll("_thumbnail(\\.[^.]*)?$", ".webp");
            // 删除原图url
            cosManager.deleteObject(userAvatarUrl);
        }
        //将url设置到user表里
        String thumbnailUrl = pictureUploadResult.getThumbnailUrl();
        User user = User.builder()
                .id(userId)
                .userAvatar(thumbnailUrl)
                .build();
        boolean update = userService.updateById(user);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR);
        //返回头像信息
        return thumbnailUrl;
    }
}